<!-- 立项变更申请 -->
<template>
	<view class="page">
		<u--form
			labelPosition="top"
			:model="model"
			ref="ErpOmcProjectApplyForm"
			:rules="rules"
			labelWidth="auto"
			:labelStyle="{
				fontSize: '14px',
				color: '#B2B2B2',
				lineHight: '20px'
			}"
		>
			<view class="basic-style">
				<u-form-item
					label="单据编号"
					prop="projectNo"
					:borderBottom="false"
					required
				>
					<u--input
						disabled
						placeholder="请输入单据编号"
						v-model="model.projectNo"
					></u--input>
				</u-form-item>
				<u-form-item
					label="申请时间"
					prop="createTime"
					:borderBottom="false"
					required
				>
					<u--input
						v-model="model.createTime"
						disabled
						placeholder="请选择申请时间"
						border="surround"
						suffixIcon="calendar-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></u--input>
				</u-form-item>
				<u-form-item
					label="申请人"
					prop="proposer"
					:borderBottom="false"
					required
				>
					<h-select-person-input
						style="width: 100%"
						disabled
						v-model="model.proposer"
						placeholder="请选择申请人"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField="model.proposer"
					></h-select-person-input>
				</u-form-item>
				<u-form-item
					label="申请部门"
					prop="proposerDeptId"
					:borderBottom="false"
					required
				>
					<h-select-depart-input
					  disabled
					  v-model="model.proposerDeptId"
					  :departName="model.proposerDeptText"
					  placeholder="请选择部门"
					  border="surround"
					  style="width: 100%"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  :title.sync="model.proposerDeptText"
					  @detail="ontenderDeptDetail"
					></h-select-depart-input>
				</u-form-item>
				<view class="basic-title-center">
					<u-line :length="120"></u-line>
					<view class="">基本信息</view>
					<u-line :length="120"></u-line>
				</view>
				
				<u-form-item
					label="选择已立项项目"
					prop="projectId"
					:borderBottom="false"
					required
					@click="prepareProjectClick"
				>
					<h-select-project-input
					  v-model="model.projectId"
					  style="width: 100%"
					  placeholder="请选择已立项项目"
					  objectField="model.projectId"
					  border="surround"
					  :projectStatus="'2'"
					  currentProjectStatus="!2"
						:proDisabled="true"
					  :dataType="'username'"
						dataIsolation="create_by"
					  :changeStatus="'unchanged'"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  @input="projectChange"/>
				</u-form-item>
				<u-form-item
					label="变更类型"
					required
					prop="projectChangeStatus"
					:borderBottom="false"
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.projectChangeStatus" 
						placeholder="请选择变更类型" 
						dictName="project_change_status"
						@input="changeType"
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					:disabled='formDisabled'/>
				</u-form-item>
				<u-form-item
                    v-if="model.projectChangeStatus === '2'"					
					label="终止时间"
					required
					prop="projectEndDate"
					:borderBottom="false"
				>
						<h-time-select
						mode="date"
						:disabled="formDisabled"
						v-model="model.projectEndDate"
						placeholder="请选择终止时间"
					></h-time-select>
				</u-form-item>
				<u-form-item
					label="是否变更项目名称"
					prop="isChangeName"
					:borderBottom="false"
				>
					<h-dict-radio v-model="model.isChangeName" dictName="YES_OR_NO" @input="inputChangeName"/>
				</u-form-item>
				<u-form-item
					v-if="model.isChangeName == 1"
					label="项目名称"
					prop="projectName"
					:borderBottom="false"
					:required="model.isChangeName == 1"
				>
					<u--input
						v-model="model.projectName"
						@change="changeTitle"
						placeholder="请输入项目名称"
						border="surround"/>
				</u-form-item>
				<u-form-item
					label="经营团队"
					prop="teamName"
					:borderBottom="false"
				>
					<h-select-team-input
					  @input="changeBusinessCompany"
						style="width: 100%;"
						v-model="model.teamName"
						objectField="model.teamName"
						placeholder="请选择经营团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						:tdlx="1" :disabled='isHasContract'/>
				</u-form-item>
				<!-- <u-form-item
				label="经营公司"
				prop="businessCompanyId"
				:borderBottom="false"
				>
				<h-select-company-input
					disabled
					style="width: 100%"
					v-model="model.businessCompanyId"
					border="surround"
					placeholder="请选择经营公司"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{color: '#B2B2B2'}"
					objectField = 'managerTrusteeForm.gsdaId'
				></h-select-company-input>
              </u-form-item> -->
				<u-form-item
					label="项目承接人"
					prop="undertaker"
					:borderBottom="false"
				>
					<h-select-person-input
						style="width: 100%"
						v-model="model.undertaker"
						placeholder="请选择项目承接人"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField="model.undertaker" :disabled='isHasContract'/>
				</u-form-item>
				
				<u-form-item
					label="立项日期"
					prop="projectEstablishDate"
					:borderBottom="false"
				>
					<h-time-select
					  v-model="model.projectEstablishDate"
					  placeholder="请选择立项日期"
					  border="surround"
					  suffixIcon="calendar-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  mode="datetime" :disabled='isHasContract'/>
				</u-form-item>
				
				<u-form-item
					label="签订单位"
					prop="signUnit"
					:borderBottom="false"
				>
					<h-select-company-input
						style="width: 100%;"
						v-model="model.signUnit"
						objectField="model.signUnit"
						placeholder="请选择签订单位"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}" :disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="业绩归属年度"
					prop="year"
					:borderBottom="false"
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.year" 
						placeholder="请选择业绩归属年度" 
						dictName="yjgsnd" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="是否环评项目"
					prop="isEnvironmentalAssessmentProject"
					:borderBottom="false"
					required
				>
					<h-dict-radio v-model="model.isEnvironmentalAssessmentProject" dictName="YES_OR_NO" :disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="业主单位"
					prop="ownerUnit"
					:borderBottom="false"
				>
					<h-select-customer-input
						style="width: 100%"
						v-model="model.ownerUnit"
						commercialType= "1"
						border="surround"
						placeholder="请选择业主单位"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField = 'model.ownerUnit'
						@input="onCustomerChange"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="联系人"
					prop="contacts"
					:borderBottom="false"
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.contacts" 
						placeholder="请选择联系人" 
						:dictName="cust_lxr" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
						@change="lxrChange"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="联系方式"
					prop="contactTel"
					:borderBottom="false"
				>
					<u--input
						v-model="model.contactTel"
						placeholder="请输入联系方式"
						border="surround"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="业主角色"
					prop="ownerRole"
					:borderBottom="false"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.ownerRole" 
						placeholder="请选择业主角色" 
						dictName="owner_role" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item
					label="企业类型"
					prop="enterpriseType"
					:borderBottom="false"
				>
				<h-dict-select
						style="width: 100%" 
						disabled
						v-model="model.enterpriseType" 
						placeholder="请选择企业类型" 
						dictName="enterprise_type" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
		
				</u-form-item>
				<u-form-item
					label="项目所在地址"
					prop="areaCode"
					:borderBottom="false"
					required
				>
					<h-select-address-input
						style="width: 100%"
						v-model="model.areaCode"
						placeholder="请选择项目地址"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="项目详细地址"
					prop="projectAddress"
					:borderBottom="false"
					required
				>
					<u--input
						placeholder="请输入项目详细地址"
						v-model="model.projectAddress"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="项目来源"
					prop="projectSource"
					:borderBottom="false"
					ref="item1"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.projectSource" 
						placeholder="请选择项目来源" 
						dictName="xmly_type"
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="预计合同额(元)"
					prop="estimatedContractAmount"
					:borderBottom="false"
					ref="item1"
					required
				>
					<h-money-input
						type="number"
						placeholder="请输入预计合同额"
						v-model="model.estimatedContractAmount"
						@change="convertMoney2"
						@blur="convertMoneyBlur2"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="预计合同额大写"
					prop="estimatedContractcapitalChineseAmount"
					:borderBottom="false"
					ref="item1"
				>
					<u--input
						disabled
						placeholder="请输入预计合同额大写"
						v-model="model.estimatedContractcapitalChineseAmount"
					></u--input>
				</u-form-item>
				<u-form-item
					label="经营绩效(元)"
					prop="businessPerformance"
					:borderBottom="false"
					ref="item1"
					required
				>
					<h-money-input
						type="number"
						placeholder="请输入经营绩效"
						v-model="model.businessPerformance"
						:disabled="isHasContract"
					></h-money-input>
				</u-form-item>
				<!-- <u-form-item label="分配方式" prop="distributionMethod" :borderBottom="false" required>
					<h-select-input-tag 
					style="width: 100%;"
					  v-model="model.distributionMethod"
					  placeholder="请选择分配方式"
					  dictName="distribution_method"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@change="getForMoney()"/>
				</u-form-item> -->
				
				<u-form-item
					label="立项事由及说明"
					prop="establishReason"
					:borderBottom="false"
					ref="item1"
				>
					<u--textarea
						v-model="model.establishReason"
						:confirmType="null"
						count
						placeholder="请输入立项事由及说明"
						:maxlength="500"
					:disabled='isHasContract'/>
				</u-form-item>
				<u-form-item
					label="立项变更事由及说明"
					prop="establishChangeReason"
					required
					:borderBottom="false"
				>
					<u--textarea
						v-model="model.establishChangeReason"
						:confirmType="null"
						count
						placeholder="请输入立项变更事由及说明"
						:maxlength="500"
					/>
				</u-form-item>
			</view>
		</u--form>
		
		<!-- 附件 -->
		<view class="basic-style">
			<view class="basic-title-center">
				<u-line :length="120"></u-line>
				<view class="">相关附件</view>
				<u-line :length="120"></u-line>
			</view>
			<view class="warning">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
			<view class="" style="width: 100%;">
				<h-upload-file v-model="model.attachment" :isIcon="false" :disabled='isHasContract'/>
				<file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
			</view>
		</view>
		<view class="basic-style">
			<view class="basic-title-center">
				<u-line :length="120"></u-line>
				<view class="">相关附件</view>
				<u-line :length="120"></u-line>
			</view>
			<view class="warning">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
			<view class="" style="width: 100%;">
				<h-upload-file v-model="model.changeAttachment" :isIcon="false" />
				<file-list v-if="model.changeAttachment" v-model="model.changeAttachment" :isDelete="true"></file-list>
			</view>
		</view>
		<view class="basic-style">
			<view class="basic-title-center">
				<u-line :length="105"></u-line>
				<view class="">任务信息</view>
				<u-line :length="105"></u-line>
			</view>
			<u-form-item label="分配方式" prop="distributionMethod" :borderBottom="false" required>
					<h-select-input-tag 
					style="width: 100%;"
					  v-model="model.distributionMethod"
					  placeholder="请选择分配方式"
					  :disabled="hasReceiptContract"
					  dictName="distribution_method"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@change="getForMoney()"/>
				</u-form-item>
				<u-form-item
					label="主生产团队"
					prop="mainProductionTeam"
					:borderBottom="false"
					required
				>
					<h-select-team-input
						style="width: 100%;"
						v-model="model.mainProductionTeam"
						objectField="model.mainProductionTeam"
						placeholder="请选择主生产团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						:tdlx="1"
					></h-select-team-input>
				</u-form-item>
			<ErpMyOmcProjectTaskForm @ok="onInforList" ref="projectTaskFormConfig" 
			:distributionMethod='model.distributionMethod' :btnShow="!isHasContract" :hasReceiptContract="isHasContract" :assignedAmount="model.estimatedContractAmount" :dataList="dataSource"/>
		</view>
		
		<view class="space-x-1 px-1 btn_position">
			<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDrafts"></u-button>
			<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
		</view>
		<view style="height: 100rpx;"></view>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
	</view>
</template>

<script>
import fileList from '@/pages/synergy/components/fileList.vue'
import ErpMyOmcProjectTaskForm from './components/ErpMyOmcProjectTaskForm.vue' // 业务分类组件
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import {
	generatedFormNumber, // 获取单据编号
	erpOmcCustomerManagerContactId, // 获取联系方式
	erpOmcProjectApplyAdd, // 添加
	erpOmcProjectApplyEdit, // 编辑
	erpOmcProjectApplyQueryById, // 详情
	erpOmcProjectApplyQueryByProjectId ,// 获取业务分类信息列表
	erpOmcProjectApplyQueryTenderResultByEntity,
	erpOmcProjectApplyQueryTenderServiceListByTenderId,
	queryByIdProjectTask,
	erpOmcProjectCheckProjectTenderEnd,
} from '@/api/index.js'
import moment from 'moment'
import http from '@/utils/request/index'
import {
	BASE_URL
} from '@/utils/baseUrl.js'
import { convertCurrency } from '@/utils/MoneyConvert' // 金额大写转换

let queryContractByProjectId='/api/erp/omc/contractmanager/erpOmcContractManagerFinal/queryContractByProjectId' //根据项目id查询合同档案里是否存在收款合同
let valdateProductTeamLeader='/api/erp/omc/project/erpOmcProjectApply/valdateEachProductTeamLeader' //校验团队生产负责人岗位是否存在
let verifyProjectAbnormalTermination='/api/erp/omc/project/erpOmcProject/verifyProjectAbnormalTermination' 
var projectId = ''
export default {
	components: {
		fileList,
		ErpMyOmcProjectTaskForm,
		ProcessNodeConfiguration
	},
	data() {
		return {
			oldProjectName: '', // 旧的项目名称
			isHasContract:false,//是否有收款合同
			isProjectId: false, // 用于判断编辑的时候不执行已立项项目详情
			isSubmit: false,
			hasReceiptContract:null,
			model: {
				applyType: '2',
				lx: '2',
				projectNo: '', //单据编号
				createTime: '', // 申请时间
				proposer: '', // 申请人
				proposerDeptId: '', // 申请部门
				projectId: '', // 已立项项目
				isChangeName: '0', // 是否变更项目名称 => 默认为否
				projectName: '', // 项目名称
				teamName: '', // 经营团队
				businessCompanyId:'', // 经营公司
				undertaker: '', // 项目承接人
				projectEstablishDate: '', // 立项日期
				signUnit: '', //签订单位
				year: '', // 业绩发归属年度
				ownerRole:'',
				changeAttachment:'',
				mainProductionTeam:'',
				projectChangeStatus:'',
				projectEndDate:'',
				establishChangeReason:'',
				enterpriseType:'',
				isEnvironmentalAssessmentProject: '0', //是否环评项目
				ownerUnit: '', // 业主单位
				contacts: '', // 联系人
				contactTel: '', // 联系方式
				areaCode: '', // 项目所在地址
				projectAddress: '', // 项目详细地址
				projectSource: '' ,// 项目来源
				estimatedContractAmount: '', // 预计合同额
				estimatedContractcapitalChineseAmount: '', // 预计合同额大写
				businessPerformance: '', // 经营绩效
				distributionMethod:'',//分配方式
				establishReason : '', // 立项事由及说明
				attachment: '', // 相关附件
			},
			cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0',
			id: '', // 详情id值
			dataSource: [], // 业务分类信息列表
			rules: {
				// projectNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				distributionMethod:[ { required: true, message: '请选择分配方式!',trigger: ['blur', 'change'] }],
				ownerRole:[ { required: true, message: '请选择业主角色!',trigger: ['blur', 'change'] }],
				mainProductionTeam:[ { required: true, message: '请选择主生产团队!',trigger: ['blur', 'change'] }],
				projectChangeStatus:[ { required: true, message: '请选择变更类型!',trigger: ['blur', 'change'] }],
				projectEndDate:[ { required: true, message: '请选择终止时间!',trigger: ['blur', 'change'] }],
				establishChangeReason:[ { required: true, message: '请输入立项变更事由及说明!',trigger: ['blur', 'change'] }],
				isEnvironmentalAssessmentProject: [
					{ required: true, message: '请选择是否环评!', trigger: ['change','blur'], },
				],
				projectId: [
					{ required: true, message: '请选择已立项项目!', trigger: ['change','blur'], },
				],
				projectName: [
					{ required: true, message: '请输入项目名称!', pattern: '[^ \x22]+', trigger: ['change','blur'] }, 
					{
						asyncValidator: (rule, value, callback) => {
							let params = {
								projectName: value,
								projectId: projectId
							}
							http.get('/api/erp/omc/project/erpOmcProject/checkProjectDuplicate', params).then(res => {
								// 如果验证不通过，需要在callback()抛出new Error('错误提示信息')
								if (res.success) {
									callback();
								} else {
									callback(new Error(res.message));
								}
							}).catch(err => {
								callback(new Error(err.message));
							})
						},
						trigger: ['blur']
					}
				],
				
				projectNo: [
					{ required: true, message: '请输入已立项项目编号!', trigger: ['change','blur'], },
				],
				areaCode: [
					{ required: true, message: '请选择项目所在地址!', trigger: ['change','blur'] },
				],
				projectAddress: [
					{ required: true, message: '请输入项目所在详细地址!', trigger: ['change','blur'] },
				],
				estimatedContractAmount: [
					{ required: true, message: '请输入预计合同额!', trigger: ['change','blur'] },
				],
				projectSource: [
					{ required: true, message: '请选择项目来源!', trigger: ['change','blur'] },
				],
				businessPerformance: [
				  { type: 'number', required: true, message: '请输入经营绩效!', trigger: ['blur'] },
				],
				contactTel: [
					{ type: 'any', required: true, message: '请输入联系电话!', trigger: ['change', 'blur'], },
					{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['change', 'blur'], }
				]
			},
			
			//代码生成后需手动设置流程编码
			flowCode: 'dev_erp_omc_project_apply_001',
			//代码生成后需手动设置流程编码
			flowCodeApply: 'dev_erp_omc_project_apply_001',
			formUrlApply: '/erp/omc/project/modules/ErpOmcProjectApplyForm',
			//代码生成后需手动设置流程编码
			flowCodeChange: 'dev_erp_omc_project_apply_002',
			formUrlChange: '/erp/omc/project/modules/ErpOmcProjectChangeForm',
			formUrl: '/erp/omc/project/modules/ErpOmcProjectApplyForm',
			beanName: 'erpOmcProjectApplyServiceImpl',
			formUrlMobile: '/pages/synergy/erpOmcProjectApplyList',
			dictOptions: {},
			superFieldList: [],
			formDisabled: false,
			processId: '1469208959040917506'
		};
	},
	onLoad(options) {
		this.id = options.id || ''
		if (options.id) {
			// 编辑
			this.edit(options.id)
		} else {
			// 添加
			this.add()
		}
		this.initDictConfig()
	},
	methods: {
		changeType(val){
          console.log(val,'val');

		  if(val === '2' || val === '3'){
			this.model.estimatedContractAmount = 0
			this.model.businessPerformance = 0
			let money = this.model.estimatedContractAmount
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(money))
			if(this.dataSource.length){
          this.dataSource.forEach(item=>{
           item.contractRate = 0   
           item.contractAmount = 0   
           item.cutContractAmount = 0
          })
        }
		  }
          if(val != '2'){
			this.model.projectEndDate = null
		  }

		  
		},

		changeBusinessCompany(val){
			this.model.businessCompanyId = val.belongCompanyId
		},


		// 是否存在收款合同
		async getContractByPro(){
	
		  let res = await http.get(queryContractByProjectId,{
			projectId:this.model.projectId
		  })
	
		  if(res.success){
	
			this.isHasContract = res.result==1?true:false
			
		  }else{
			this.$u.toast(res.message||'查询是否存在收款合同失败！')
		  }
	
		},
		// 加载数据字典信息
		initDictConfig() {
			initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'productTeam', res.result)
				}
			})
		},
		
		// 编辑
		async edit(id) {
			// 获取详情
			this.getDetail(id)
			queryByIdProjectTask({ id: id == null ? '1' : id }).then(res => {
				if (res.result) {
					this.dataSource = res.result
				}
			})
			
		},
		// 获取详请
		getDetail (id) {
			erpOmcProjectApplyQueryById({ id }).then(async res => {
				if (res.success) {
					this.model = await {...res.result};
					this.model.contacts = res.result.contacts
					this.model.contactTel = res.result.contactTel
					this.oldProjectName = res.result.projectId_dictText
					projectId = this.model.projectId
					this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + res.result.ownerUnit + '\'';
					if (this.model.estimatedContractAmount) {
						this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(this.model.estimatedContractAmount))
						this.model.estimatedContractAmount = this.model.estimatedContractAmount.toFixed(2)
					}
					
					this.getContractByPro()
					
				}
			})
		},
		
		// 选择变更项目名称
		inputChangeName (val) {
			if (val == 1) {
				// this.$set(this.rules, 'projectName', [{ required: true, message: '请输入项目名称!', pattern: '[^ \x22]+', trigger: ['change','blur'] }, { validator: checkProjectName, trigger: 'blur' }])
			} else {
				this.$set(this.model, 'projectName', this.oldProjectName)
				// this.$delete(this.rules, 'projectName')
			}
		},
		// 修改项目名称修改流程标题
		changeTitle() {
			this.$set(this.model, 'bpmBizTitle', this.model.projectName)
		},
		
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				let formUrl = this.formUrlApply;
				let flowCode = this.flowCodeApply;
				//判定流程的类型
				if (this.model.lx) {
					if (this.model.lx == 2) {
						formUrl = this.formUrlChange;
						flowCode = this.flowCodeChange;
					}
				}
				var projectId = this.model.finalProjectId ? this.model.finalProjectId : this.model.projectId
				// 校验该预立项是否存在，如果存在则无法提交
				erpOmcProjectCheckProjectTenderEnd({ id: projectId, type: this.model.lx, isPrepareEstablish: this.model.isPrepareEstablish }).then(res => {
					if (res.success) {
						this.$refs.processConfig.showPopup = true
						this.$refs.processConfig.formUrl = formUrl
						this.$refs.processConfig.formUrlMobile = this.formUrlMobile
						this.$refs.processConfig.flowCode = flowCode
						this.$refs.processConfig.edit(id, this.processId, this.beanName)
					} else {
						this.$refs.uToast.show({
							message: res.message,
							complete () {
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
								
							}
						})
					}
				})
			}
		},
		
		// 投标部门详情
		ontenderDeptDetail(item) {
		  var title = ''
		  if (item && item.length) {
		    item.map((value, index) => {
		      title = value.departName + ',' + title
		    })
		    title = title.substring(0, title.lastIndexOf(','))
		  }
		  this.model.proposerDeptText = title
		},
		
		// 点击预立项
		prepareProjectClick () {
			this.isProjectId = true
		},
		
		// 选择预立项
		projectChange (project) {
			// 人为的判断是否点击改变值
			if (!this.isProjectId) {
				// 当点击编辑的时候，不执行下面
				return false
			}
			this.$set(this.model, 'projectId', project.id)
			projectId = project.id
			this.$set(this.model, 'finalProjectId', project.id) // 控制提交流程时，任务档案反写是否变更状态
			this.$set(this.model, 'bpmBizTitle', project.projectName)// 标题
			this.$set(this.model, 'isPrepareEstablish', project.isPrepareEstablish)
			this.$set(this.model, 'projectName', project.projectName)
			this.oldProjectName = project.projectName
			this.hasReceiptContract = project.hasReceiptContract
			console.log(project,'project---');
			this.$set(this.model, 'projectType', project.projectType)
			this.$set(this.model, 'teamName', project.oldTeamId ? project.oldTeamId : project.teamName)
			this.$set(this.model, 'businessCompanyId', project.businessCompanyId)
			this.$set(this.model, 'undertaker', project.undertaker)
			this.$set(this.model, 'isBidding', project.isBidding)
			this.$set(this.model, 'isEnvironmentalAssessmentProject', project.isEnvironmentalAssessmentProject)
			this.$set(this.model, 'signUnit', project.signUnit)
			this.$set(this.model, 'year', project.year + '')
			this.$set(this.model, 'ownerUnit', project.ownerUnit)
			this.$set(this.model, 'ownerRole', project.ownerRole)
			this.$set(this.model, 'enterpriseType', project.enterpriseType)
			this.$set(this.model, 'contacts', project.contacts)
			this.$set(this.model, 'contactTel', project.contactTel)
			this.$set(this.model, 'areaCode', project.areaCode)
			this.$set(this.model, 'projectAddress', project.projectAddress)
			this.$set(this.model, 'projectSource', project.projectSource)
			this.$set(this.model, 'mainProductionTeam', project.mainProductionTeam)
			this.$set(this.model, 'estimatedContractAmount', project.estimatedContractAmount)
			this.$set(this.model, 'businessPerformance', project.businessPerformance)
			this.$set(this.model, 'distributionMethod', project.distributionMethod)
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', project.estimatedContractcapitalChineseAmount)
			this.$set(this.model, 'establishReason', project.establishReason === null ? '' : project.establishReason)
			// this.$set(this.model, 'establishReason', project.establishReason)
			this.$set(this.model, 'attachment', project.attachment)
			this.$set(this.model, 'applyType', '2')
			this.$set(this.model, 'lx', '2')
			this.$set(this.model, 'projectNo', project.projectNo)
			this.$set(this.model, 'projectEstablishDate', project.projectEstablishDate)// 立项日期

			if(this.model.projectChangeStatus === '2' || this.model.projectChangeStatus === '3'){
				this.model.estimatedContractAmount = 0
				this.model.businessPerformance = 0
				let money = this.model.estimatedContractAmount
				this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(money))
			}
			
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
			// 根据项目id 查看业务分类
			this.dataSource = []
			
			this.getContractByPro()
			
			erpOmcProjectApplyQueryByProjectId({ projectId: this.model.projectId }).then(res => {
				if (res.success) {
					this.dataSource = res.result.records || res.result
                    if(this.dataSource.length){
						if(this.model.projectChangeStatus === '2' || this.model.projectChangeStatus === '3'){
							this.dataSource.forEach(item=>{
								item.contractRate = 0   
								item.contractAmount = 0   
								item.cutContractAmount = 0
          })
						}
					}
               

				}
			})
			this.convertMoneyBlur2(project.estimatedContractAmount)
			this.$refs.ErpOmcProjectApplyForm.clearValidate() // 清空校验结果
			
			this.isProjectId = false
		},
		
		// 添加
		add() {
			// this.getGeneratedFormNumber()
			this.model.createTime = moment().format('YYYY-MM-DD HH:mm'); // 申请时间
			this.model.proposer = uni.getStorageSync('userInfo').empId; //申请人
			this.model.proposerDeptId = uni.getStorageSync('userInfo').deptId; //申请部门
			projectId = ''
		},
		// 获取单据编号
		getGeneratedFormNumber() {
			generatedFormNumber({ prefix: 'YLX', subSystemCode: '05' }).then(res => {
				if (res.success) {
					this.$set(this.model, 'projectNo', res.result)
				}
			})
		},
		
		// 修改本次合同额大写和修改任务信息中的合同占比
		convertMoney2(item) {

			console.log('走了吗--change');
			
			if (this.model.estimatedContractAmount === null
				|| this.model.estimatedContractAmount === ''
				|| this.model.estimatedContractAmount === undefined) {
					this.$set(this.model, 'estimatedContractcapitalChineseAmount', '')
				return false
			}
			let money = Number(this.model.estimatedContractAmount)
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(money))
			this.getForMoney()
		},
		getForMoney(){
		  if(this.dataSource.length>0){
	
			this.dataSource.forEach(item =>{
	
			  if(parseInt(this.model.estimatedContractAmount)===0){
				item.contractAmount = 0
				item.contractRate = 0
				
			  }else{
	
				if(!this.model.estimatedContractAmount){
				  return
				}
	
				if(this.model.distributionMethod=='1'){
				  // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
				  if(item.contractRate){
	
					let amount = this.model.estimatedContractAmount * item.contractRate / 100
					item.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100
	
					// item.contractAmount = parseFloat(item.contractRate*0.01*parseFloat(this.model.estimatedContractAmount)).toFixed(2)
	
				  }
	
			  }else if(this.model.distributionMethod=='2'){
				// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
				if(item.contractAmount){
	
				  let rate = item.contractAmount / this.model.estimatedContractAmount * 100
				  item.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100
					// item.contractRate = parseFloat(parseFloat(item.contractAmount) / parseFloat(this.model.estimatedContractAmount)*100).toFixed(2)
				  }
				}
	
			  }
	
			})
		  }
		},
		// 监听修改本次合同额数据
		convertMoneyBlur2 (item) {
			console.log('走了吗--blur');
			
			if (this.model.estimatedContractAmount === null
				|| this.model.estimatedContractAmount === ''
				|| this.model.estimatedContractAmount === undefined) {
					this.$set(this.model, 'estimatedContractcapitalChineseAmount', '')
				return false
			}
			let money = Number(this.model.estimatedContractAmount)
			if (money <= 0) {
				money = 0
			}
			this.$set(this.model, 'estimatedContractAmount', money.toFixed(2))
			this.convertMoney2()
		},
		
		// 选择业主单位
		onCustomerChange (val) {
			this.$set(this.model, 'contacts', null)
			this.$set(this.model, 'contactTel', '')
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
			this.model.enterpriseType = val.enterpriseType
		},
		// 选择联系人
		lxrChange (val) {
			var params = {id: val}
			erpOmcCustomerManagerContactId(params).then(res => {
				if (res.success) {
					this.$set(this.model, 'contactTel', res.result.lxfs)
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		onInforList (item,type) {
			let params = JSON.parse(JSON.stringify(item))
			// 区分编辑or新增
			if(type=='add'){
				this.dataSource.push(params)
			}else if(type=='edit'){
				for (let it of this.dataSource) {
					if(it.id===params.id){
						// it = {...params}
						for (const key in params) {
							if (Object.hasOwnProperty.call(it, key)) {
							  it[key] = params[key]
							}
						}
					}
				}
				this.$forceUpdate()
			}else if(type=='delete'){
				this.dataSource.splice(item, 1)
			}
			
		},
		
		validateForm() {
			return this.$refs.ErpOmcProjectApplyForm.validate().then(async () => {
			var that = this
			if (this.model.isChangeName && this.model.isChangeName == '1') {
				let params = {
					projectName: that.model.projectName,
					projectId: projectId,
					type: 'project' // 立项：project  预立项：prepare
				}
				return http.get('/api/erp/omc/project/erpOmcProject/checkProjectDuplicate', params).then(async res => {
					// 如果验证不通过，需要在callback()抛出new Error('错误提示信息')
					if (!res.success) {
						return Promise.reject(res.message)
					}
				}).catch(async err => {
					return Promise.reject(err.message)
				})
			}
				if (this.dataSource == null || this.dataSource.length <= 0) {
					this.$refs.uToast.show({
						message: '必须填写业务分类信息！',
						type: 'error'
					})
					return Promise.reject('必须填写业务分类信息！')
				}
				
				// 判断是按比例还是按金额
				if(this.model.distributionMethod=='1'){
				          
				  let rate = 0
				  this.dataSource.forEach(val => {
					rate += parseFloat(val.contractRate)
				  })
				  if(rate!=100&&parseInt(this.model.estimatedContractAmount)!==0){
					  this.$refs.uToast.show({
					  	message: '合同占比相加不等于100%，请重新填写',
					  	type: 'error'
					  })
					return Promise.reject('合同占比相加不等于100%，请重新填写')
				  }
						
				}else if(this.model.distributionMethod=='2'){
				  let total = 0
				  this.dataSource.forEach(val => {
					total += parseFloat(val.contractAmount)
				  })
				  if (total.toFixed(2) != parseFloat(that.model.estimatedContractAmount).toFixed(2)) {
					this.$refs.uToast.show({
						message: '所有分配金额总计和预计合同额不相等，请重新填写！',
						type: 'error'
					})
					return Promise.reject('所有分配金额总计和预计合同额不相等，请重新填写！')
				  }
				}
				// this.isSubmit = true
				// var isJudge = -1
				// for (var i = 0; i < this.dataSource.length; i++) {
				// 	var isTrue = await http.get('/api/erp/omc/project/erpOmcProjectApply/valdateProductTeamLeader', { teamId: this.dataSource[i].productTeam }).then((res) => {
				// 		if (res.success) {
				// 			return res.success
				// 		} else {
				// 			isJudge = i
				// 			var info = filterMultiDictText(this.dictOptions['productTeam'], this.dataSource[i].productTeam + '') + '团队，生产负责人岗位未找到'
				// 			this.$refs.uToast.show({
				// 				message: info,
				// 				type: 'error'
				// 			})
				// 			return res.success
				// 		}
				// 	})
				// 	if (!isTrue) {
				// 		break
				// 	}
				// }
				// this.isSubmit = false
				// if (isJudge != -1) {
				// 	return Promise.reject('生产负责人岗位未找到')
				// }
				
				let teamIdArr = []
				for (let it of this.dataSource) {
					let params = {
					  teamId:it.productTeam,
					  productTeam: filterMultiDictText(this.dictOptions['productTeam'], it.productTeam + '')
					}
					teamIdArr.push(params)
				}

				// // 去重
				// var newArr = teamIdArr.filter(function(item,index){
				// 	return teamIdArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
				// });

				let rr = await http.post(valdateProductTeamLeader,teamIdArr)
				if(!rr.success){
					this.$u.toast(rr.message)
					return Promise.reject('rr.message')
				}
				
			})
		},
		
		// 点击提交
		async onSubmit () {
			var that = this
			console.log(this.model.estimatedContractAmount,'this.model.estimatedContractAmount---');
			await this.validateForm()
			if(!this.model.distributionMethod) return 	this.$refs.uToast.show({message: '请填写分配方式',type: 'error'})
			if(!this.model.mainProductionTeam) return 	this.$refs.uToast.show({message: '请填写主生产团队',type: 'error'})
			
			this.model.categoryList = this.dataSource;
			let httpurl = '';

			if (!this.id) {
				httpurl = erpOmcProjectApplyAdd;
			} else {
				httpurl = erpOmcProjectApplyEdit;
			}
			 
			if(this.model.projectChangeStatus === '2' && this.model.estimatedContractAmount !== '0.00') return this.$refs.uToast.show({message: '预计合同额不为0',type: 'error'})
			if(this.model.projectChangeStatus === '3' && this.model.estimatedContractAmount !== '0.00') return this.$refs.uToast.show({message: '预计合同额不为0',type: 'error'})
			const result = await http.get(verifyProjectAbnormalTermination,{
				id:this.model.projectId,
				type:this.model.projectChangeStatus
			}) 
			if(!result.success) return this.$refs.uToast.show({message: result.message,type: 'error'})
			// console.log(!result.success);
			this.isSubmit = true
			httpurl(this.model).then(res => {
				if (res.success) {
					var that = this
					// 获取流程列表
					if (this.id) {
						this.getProcessList(this.id)
					} else {
						// 判断添加的时候是否有返回id值
						if (res.result) {
							this.getProcessList(res.result)
						}
					}
					this.$refs.uToast.show({
						message: res.message,
						type: 'default',
						complete () {
							// that.isSubmit = false
						}
					})
					
					
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		async onDrafts() {
			var that = this
			// await this.validateForm()
			
			this.isSubmit = true
			this.model.categoryList = this.dataSource;
			let httpurl = '';
			if (!this.id) {
				httpurl = erpOmcProjectApplyAdd;
			} else {
				httpurl = erpOmcProjectApplyEdit;
			}
			httpurl(this.model).then(res => {
				if (res.success) {
					var that = this
					this.$refs.uToast.show({
						message: res.message,
						type: 'default',
						complete () {
							that.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
					
					
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
	}
};
</script>

<style lang="scss" scoped>
@import url("@/assets/inputStyle.scss");
.basic-title-center {
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 16px;
	font-family: PingFangSC-Medium, PingFang SC;
	font-weight: 600;
	color: #333333;
	text-align: center;
}

// 评测信息
.info-title{
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #171717;
	line-height: 40rpx;
	padding-bottom: 16rpx;
}

// 评测结果
.result-style{
	font-size: 12px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #B2B2B2;
}

.inforamtion{
	margin-top: 10rpx;
	padding: 10rpx;
	border-radius: 15rpx;
	box-shadow: 0px 4px 20px 0px rgba(0,0,0,0.1);
}
.warning{
	color: #f56c6c;
	margin-bottom: 20rpx;
}
</style>